/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MyPomodoro.java
 *
 * Created on Aug 12, 2011, 12:03:39 AM
 */
package com.mypomodoro;

import com.mypomodoro.StateModel.PomodoroStates;
import java.text.DecimalFormat;

/**
 *
 * @author lifsong
 */
@SuppressWarnings("serial")
public class MyPomodoro extends javax.swing.JFrame {
    
    final String stateStrings[] = {"Start", "Break", "Continue"};    
    final StateModel stateModel;
    final TimerModel timerModel;
    private Integer workingTimerLeft;
    
    /** Creates new form MyPomodoro */
    public MyPomodoro() {
        initComponents();
        
        stateModel = new StateModel();
        timerModel = new TimerModel();
        
        timerModel.createTimer();
        addModelListeners();     
        
        workingTimerLeft = timerModel.ONE_POMODORO_SECONDS;
    }

    private void addModelListeners() {
        stateModel.addModelListener(new StateModelListener ()
          {
            public void modelChanged (final StateModel stateModel)
            {
              setStartButtonText(stateModel.state.getValue());
              if(stateModel.state.getValue() == PomodoroStates.WORKING_STATE){
                  timerModel.timerLeftSec.setValue(workingTimerLeft);
                  timerModel.restartTimer();
              }else if(stateModel.state.getValue() == PomodoroStates.BREAK_STATE){
                  workingTimerLeft = timerModel.timerLeftSec.getValue();
                  timerModel.restartTimer();
                  timerModel.timerLeftSec.setValue(timerModel.BREAK_POMODORO_SECONDS);
              }
            }
          });   
        
        timerModel.addModelListener(new TimerModelListener ()
          {
            public void modelChanged (final TimerModel timerModel)
            {
              setTimingLabelText(timerModel.timerLeftSec.getValue());
              
              if(timerModel.timerLeftSec.getValue() == 0){
                
                timerModel.stopTimer();
                stateModel.setNextStateWhenTimerExpired(stateModel.state.getValue());

                if(stateModel.state.getValue() == PomodoroStates.INIT_STATE){
                  workingTimerLeft = timerModel.ONE_POMODORO_SECONDS;
                  timerModel.timerLeftSec.setValue(workingTimerLeft);
                  setTimingLabelText(timerModel.timerLeftSec.getValue());
                }
              }
            }
          });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelTiming = new javax.swing.JLabel();
        jButtonStart = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("My Pomodoro");
        setAlwaysOnTop(true);
        setBackground(java.awt.Color.white);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("framMyPomodoro"); // NOI18N
        setResizable(false);

        jLabelTiming.setBackground(java.awt.SystemColor.window);
        jLabelTiming.setFont(jLabelTiming.getFont().deriveFont(jLabelTiming.getFont().getStyle() | java.awt.Font.BOLD, jLabelTiming.getFont().getSize()+22));
        jLabelTiming.setForeground(new java.awt.Color(42, 45, 221));
        jLabelTiming.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelTiming.setText("25:00"); // NOI18N
        jLabelTiming.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, java.awt.SystemColor.activeCaptionBorder));

        jButtonStart.setFont(jButtonStart.getFont().deriveFont((jButtonStart.getFont().getStyle() | java.awt.Font.ITALIC) | java.awt.Font.BOLD, jButtonStart.getFont().getSize()+2));
        jButtonStart.setText("Start");
        jButtonStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonStartActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelTiming, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButtonStart, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(23, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButtonStart, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabelTiming, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 37, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStartActionPerformed
    stateModel.setNextStateWhenUserAction(stateModel.state.getValue());
}//GEN-LAST:event_jButtonStartActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MyPomodoro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyPomodoro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyPomodoro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyPomodoro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MyPomodoro().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonStart;
    private javax.swing.JLabel jLabelTiming;
    // End of variables declaration//GEN-END:variables
    
    private void setStartButtonText(StateModel.PomodoroStates state){
        jButtonStart.setText(stateStrings[state.ordinal()]);
    }
    
    private void setTimingLabelText(Integer lefSec){
        jLabelTiming.setText(formatTime(lefSec));
    }    
    
    private String formatTime(int seconds) {
        DecimalFormat formatter = new DecimalFormat("00");
        String mins = formatter.format(seconds / 60);
        String sec = formatter.format(seconds % 60);
        return mins + ":" + sec;
    }    
}
